package huang.controller;

import huang.domain.User;
import huang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Creat by 黄伟洪 on 2021/7/19 18:20
 */
@Controller
public class UserController {
    @Autowired
    UserService userService;

    /*访问登录页面*/
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    /*验证登录*/
    @RequestMapping("/login")
    public String login(User user, Model model, HttpServletRequest request) {

        /*调用验证登录的逻辑类去验证登录*/
        if (userService.checkLogin(user.getU_name(), user.getU_password(), request)) {
            model.addAttribute("tips", "登录成功");
            model.addAttribute("User", user);
            return "index";
        } else {
            model.addAttribute("msg", "用户名或密码错误！");
            return "login";
        }
    }

    /*退出登录*/
    @RequestMapping("/removeLogin")
    public String removeLogin(HttpServletRequest request) {
        userService.clearSession(request);
        System.out.println("退出账号成功！");
        return "index";
    }

    /*访问注册页面*/
    @RequestMapping("/toRegist")
    public String toRegist() {
        return "regist";
    }

    /*注册账号*/
    @RequestMapping("/regist")
    public String regist(User user, Model model) {

        /*验证是否注册成功*/
        if (userService.addUser(user.getU_name(), user.getU_password(), user.getU_phone())) {
            System.out.println("注册成功");
            model.addAttribute("User", user);
            return "login";
        } else {
            System.out.println("注册失败");
            return "regist";
        }
    }

    /*访问修改个人信息页面*/
    @RequestMapping("/toUpdateUser")
    public String toUpdateUser() {
        return "user_update";
    }

    /*修改密码*/
    @RequestMapping("/updatePwd")
    @ResponseBody
    public Map<String,Object> updatePwd(String id, String oldPwd, String newPwd) {
        System.out.println("进入修改密码的控制器！");
        System.out.println(id+oldPwd+newPwd);

        /*调用AdminService内的修改密码的业务*/
        boolean updateResult = userService.updatePwd(Integer.parseInt(id),oldPwd,newPwd);

        HashMap<String,Object> map = new HashMap<>();
        if(updateResult==true) {
            map.put("code",0);
        } else {
            map.put("code",-1);
        }
        return map;
    }


    @RequestMapping("/findAll")
    public String findAll() {

        System.out.println(userService.getAllUsers().toString());
        return "login";
    }


}
